package operator.function.do_;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import util.Printer;
import util.ThreadHelper;

class DoOnLifecycleOperator {

    public static void main(String[] args) {
        doOnLifecycle();
    }

    static void doOnLifecycle() {
        Observable.interval(1, TimeUnit.SECONDS)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        Printer.print("doOnLifecycle doOnSubscribe1 disposable = " + disposable);
                    }
                })
                .doOnDispose(new Action() {
                    @Override
                    public void run() throws Exception {
                        Printer.print("doOnLifecycle doOnDispose1");
                    }
                })
                .doOnLifecycle(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        Printer.print("doOnLifecycle doOnSubscribe2 disposable " + disposable);
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        Printer.print("doOnLifecycle doOnDispose2");
                    }
                })
                .subscribe(new Observer<Long>() {

                    Disposable disposable;

                    @Override
                    public void onSubscribe(Disposable disposable) {
                        Printer.print("doOnLifecycle onSubscribe");
                        this.disposable = disposable;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        Printer.print("doOnLifecycle onNext aLong = " + aLong);
                        if(aLong == 3){
                            Printer.print("doOnLifecycle onNext中解除订阅");
                            disposable.dispose();
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }

                    @Override
                    public void onComplete() {
                        Printer.print("doOnLifecycle onComplete");
                    }
                });

        ThreadHelper.sleep();
    }


}
